package jp.co.rc.controller;

import com.github.pagehelper.util.StringUtil;
import jp.co.rc.common.AjaxResult;
import jp.co.rc.entity.User;
import jp.co.rc.service.UserServiceI;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.validation.constraints.Max;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import java.util.List;


@Validated
@Slf4j
@RequestMapping("/user")
@Controller
public class UserController {

    @Autowired
    UserServiceI userServiceI;

    @PostMapping("createUser")
    public int createUser(@RequestBody @Validated User user) {
        return userServiceI.createUser(user);
    }

    @RequestMapping("getUserById")
    public AjaxResult getUserById(
            @Max(message = "长度错误", value = 10) Integer id) {
        User user = userServiceI.getUserById(id);


        return AjaxResult.success(user);
    }


    @RequestMapping("getAllUser")
    public AjaxResult getAllUser() {
        List<User> allUser = userServiceI.getAllUser();
        return AjaxResult.success(allUser);
    }


    @DeleteMapping("deleteById")
    public int deleteById(@NotNull(message = "不能为空") @Size(max = 10000, min = 1, message = "长度需要在1-10000之间") int id) {
        return userServiceI.deleteById(id);
    }

    @PostMapping("updateById")
    public int updateById(@NotNull(message = "不能为空") @Size(max = 16, min = 6, message = "字符串长度需要在6-16之间") String name,
                          @NotNull(message = "不能为空") @Size(max = 18, min = 6, message = "字符串长度需要在6-18之间") String password,
                          @NotNull(message = "不能为空") @Size(max = 10000, min = 1, message = "长度需要在1-10000之间") String id) {
        return userServiceI.updateById(name, password, id);
    }

    @PostMapping("login")
    public ModelAndView login(@NotBlank(message = "username") String username,
                              @NotBlank(message = "password") @Size(max = 16, min = 6, message = "password") String pwd) {
        ModelAndView md = new ModelAndView();
        if (username == null || pwd == null) {
            md.setViewName("error");
            md.addObject("message", "pwd");
            return md;
        }
        md.setViewName("user/toUser");
        User userByData = userServiceI.getUserByData(username, pwd);
        if (StringUtils.isEmpty(userByData)) {
            md.setViewName("error");
            md.addObject("message", "user is not find");
            return md;
        }
        md.addObject("user", userByData);
        return md;
    }
}
